package com.zrrd.jt_admin.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zrrd.jt_admin.common.bo.OrderBo;
import com.zrrd.jt_admin.common.entity.Orders;
import com.zrrd.jt_admin.common.entity.OrderItem;
import com.zrrd.jt_admin.common.entity.User;
import com.zrrd.jt_admin.common.vo.OrderPageVo;
import com.zrrd.jt_admin.order.mapper.OrderMapper;
import com.zrrd.jt_admin.order.service.OrderItemService;
import com.zrrd.jt_admin.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.jt_admin.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhangYK
 * @since 2024-07-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private UserService userService;

    /**
     * 分页查询
     * @param pageNo
     * @param pageSize
     * @param tab
     * @param no
     * @param startTime
     * @param endTime
     * @param name
     * @param phone
     * @return
     */
    @Override
    public OrderPageVo findByPage(Integer pageNo, Integer pageSize, String tab, String no, String startTime, String endTime, String name, String phone) {
        PageHelper.startPage(pageNo, pageSize);
        List<Orders> orders = lambdaQuery()
                .like(StringUtils.isNotBlank(no), Orders::getNo,no)
                .between(StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime), Orders::getCreateTime,startTime,endTime)
                .like(StringUtils.isNotBlank(name), Orders::getAddress,name)
                .like(StringUtils.isNotBlank(phone), Orders::getAddress,phone)
                .list();
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(orders);
        List<OrderBo> list = orders.stream().map(order -> {
            OrderBo orderBo = new OrderBo();
            BeanUtils.copyProperties(order, orderBo);
            List<OrderItem> orderItems = orderItemService.lambdaQuery()
                    .eq(OrderItem::getOrderId, order.getId())
                    .list();
            orderBo.setOrderItems(orderItems);
            User user = userService.getById(order.getUserId());
            orderBo.setUser(user);
            return orderBo;
        }).collect(Collectors.toList());
        OrderPageVo orderPageVo = new OrderPageVo();
        orderPageVo.setList(list);
        orderPageVo.setTotalCount(pageInfo.getTotal());
        return orderPageVo;
    }
}
